<template>
  <div>
    <div class="output_sink">
      <TabPoint :pointList="pointList"> </TabPoint>
      <div id="pointBox" class="option_box">
        <el-form
          ref="formName"
          style="width: 100%"
          label-position="top"
          :model="form"
        >
          <div class="title" id="option">选项</div>
          <el-form-item label="选择类型">
            <el-select
              filterable
              size="small"
              v-model="form.type"
              placeholder="请输入或选择类型"
              @change="changeType"
            >
              <el-option
                v-for="item in sources"
                :key="item.name"
                :value="item.name"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <div v-if="form.type">
            <div v-if="form.sourceList.length !== 0">
              <div v-for="(item, index) in form.sourceList" :key="item.zhName">
                <!-- 表单验证这里必须是form的直接子属性  sourceList.' + index + '.defaultValue'-->
                <!-- {{ item.type[0] }} -->
                <el-form-item
                  :prop="'sourceList.' + index + '.defaultValue'"
                  :rules="[
                    {
                      required: true,
                      message: item.zhName + '不能为空',
                      trigger: 'blur',
                    },
                    {
                      validator(rule, value, callback) {
                        validatorForm(rule, value, callback, item);
                      },
                      trigger: 'blur',
                    },
                  ]"
                  :label="item.zhName"
                  v-if="item.optional === false"
                >
                  <!-- item.type[0] -->
                  <el-radio-group
                    v-model="item.defaultValue"
                    v-if="item.type && item.type[0] === 'BOOL'"
                  >
                    <el-radio :label="true">是</el-radio>
                    <el-radio :label="false">否</el-radio>
                  </el-radio-group>
                  <el-input
                    v-else
                    size="small"
                    v-model="item.defaultValue"
                    :show-password="item.zhName.indexOf('密码') != -1"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  v-else
                  :prop="'sourceList.' + index + '.defaultValue'"
                  :rules="[
                    {
                      required: false,
                      validator(rule, value, callback) {
                        validatorForm(rule, value, callback, item);
                      },
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-checkbox slot="label" v-model="item.isCheck">{{
                    item.zhName
                  }}</el-checkbox>
                  <div v-if="item.isCheck">
                    <!-- 判断是否是BOOL类型的(bool显示单选组其他显示输入框) -->
                    <el-radio-group
                      v-model="item.defaultValue"
                      v-if="item.type && item.type[0] === 'BOOL'"
                    >
                      <el-radio label="true">是</el-radio>
                      <el-radio label="false">否</el-radio>
                    </el-radio-group>
                    <el-input
                      v-else
                      size="small"
                      v-model="item.defaultValue"
                      :show-password="item.zhName.indexOf('密码') != -1"
                    ></el-input>
                  </div>
                </el-form-item>
              </div>
            </div>
            <el-form-item label="自定义选项">
              <div class="key_value_list">
                <div class="key_val_list">
                  <KeyValue
                    :propKey="'customOption.' + index + '.name'"
                    :propVal="'customOption.' + index + '.defaultValue'"
                    :rulesKey="[
                      {
                        required: true,
                        message: '值不能为空',
                        trigger: 'blur',
                      },
                      {
                        validator(rule, value, callback) {
                          validator(rule, value, callback);
                        },
                        trigger: 'blur',
                      },
                    ]"
                    :rulesVal="{
                      required: true,
                      message: '值不能为空',
                      trigger: 'blur',
                    }"
                    v-model="form.customOption[index]"
                    v-for="(item, index) in form.customOption"
                    :key="index"
                    @handDel="handDel(index, 'customOption')"
                  ></KeyValue>
                </div>
                <div class="key_v_btn" @click="handAddOption('customOption')">
                  <i
                    style="font-size: 12px; color: #666; margin-right: 10px"
                    class="el-icon-plus"
                  ></i>
                  <span> 添加 </span>
                </div>
              </div>
            </el-form-item>
            <div class="title" style="margin-top: 20px" id="MAP">MAP</div>
            <el-form-item label="MAP映射类型">
              <el-select
                filterable
                size="small"
                v-model="form.mapping"
                placeholder="请选择"
                @change="changeMap"
              >
                <el-option
                  v-for="item in mapList"
                  :key="item.name"
                  :value="item.name"
                  :label="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
            <div v-for="(item, index) in form.mapList" :key="item.name">
              <el-form-item
                :prop="'mapList.' + index + '.defaultValue'"
                :rules="{
                  required: true,
                  message: item.zhName + '不能为空',
                  trigger: 'blur',
                }"
                :label="item.zhName"
                v-if="item.optional === false"
              >
                <el-radio-group
                  v-model="item.defaultValue"
                  v-if="item.type && item.type[0] === 'BOOL'"
                >
                  <el-radio :label="true">是</el-radio>
                  <el-radio :label="false">否</el-radio>
                </el-radio-group>
                <el-input
                  v-else
                  size="small"
                  v-model="item.defaultValue"
                  :show-password="item.zhName.indexOf('密码') != -1"
                ></el-input>
              </el-form-item>
              <el-form-item v-else>
                <el-checkbox slot="label" v-model="item.isCheck">{{
                  item.zhName
                }}</el-checkbox>
                <div v-if="item.isCheck">
                  <el-radio-group
                    v-model="item.defaultValue"
                    v-if="item.type && item.type[0] === 'BOOL'"
                  >
                    <el-radio :label="true">是</el-radio>
                    <el-radio :label="false">否</el-radio>
                  </el-radio-group>
                  <!-- <el-input size="small" v-model="item.defaultValue"></el-input> -->
                  <el-input
                    v-else
                    size="small"
                    v-model="item.defaultValue"
                    :show-password="item.zhName.indexOf('密码') != -1"
                  ></el-input>
                </div>
              </el-form-item>
            </div>
            <el-form-item label="自定义选项">
              <div class="key_value_list">
                <div class="key_val_list">
                  <KeyValue
                    :propKey="'customOptionMAP.' + index + '.name'"
                    :propVal="'customOptionMAP.' + index + '.defaultValue'"
                    :rulesKey="[
                      {
                        required: true,
                        message: '值不能为空',
                        trigger: 'blur',
                      },
                      {
                        validator(rule, value, callback) {
                          validator(rule, value, callback);
                        },
                        trigger: 'blur',
                      },
                    ]"
                    :rulesVal="{
                      required: true,
                      message: '值不能为空',
                      trigger: 'blur',
                    }"
                    v-model="form.customOptionMAP[index]"
                    v-for="(item, index) in form.customOptionMAP"
                    :key="index"
                    @handDel="handDel(index, 'customOptionMAP')"
                  ></KeyValue>
                </div>

                <div
                  class="key_v_btn"
                  @click="handAddOption('customOptionMAP')"
                >
                  <i
                    style="font-size: 12px; color: #666; margin-right: 10px"
                    class="el-icon-plus"
                  ></i>
                  <span> 添加 </span>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="">
              <el-checkbox slot="label" v-model="form.isCorresponding"
                >MAP对应关系</el-checkbox
              >
            </el-form-item>
            <!--根据后一个节点属性添加 -->
            <el-form-item label="" v-if="form.isCorresponding">
              <div class="key_value_list key_val_list">
                <KeyValue
                  :propKey="'attributeList.' + index + '.name'"
                  :propVal="'attributeList.' + index + '.defaultValue'"
                  :rulesKey="[
                    {
                      required: true,
                      message: '值不能为空',
                      trigger: 'blur',
                    },
                    {
                      validator(rule, value, callback) {
                        validator(rule, value, callback);
                      },
                      trigger: 'blur',
                    },
                  ]"
                  :rulesVal="{
                    required: true,
                    message: '值不能为空',
                    trigger: 'blur',
                  }"
                  :disabled="true"
                  v-model="form.attributeList[index]"
                  v-for="(item, index) in form.attributeList"
                  :key="index"
                  :isDel="false"
                ></KeyValue>
                <!-- <div class="key_v_btn" @click="handAddOption('attributeList')">
                <i
                  style="font-size: 12px; color: #666; margin-right: 10px"
                  class="el-icon-plus"
                ></i>
                <span> 添加 </span>
              </div> -->
              </div>
            </el-form-item>
            <!-- <el-form-item label="属性内容" v-if="form.isKeyAtt == 'PAYLOAD'">
                <el-input
                  type="textarea"
                  :rows="3"
                  placeholder="请输入内容"
                  v-model="form.attTextarea"
                >
                </el-input>
              </el-form-item> -->
          </div>
        </el-form>
      </div>
    </div>
    <!-- 确认取消公共组件 -->
    <TopOperationButton @submit="submit" @handClose="handClose" />
  </div>
</template>

<script>
import TabPoint from "@/components/TabPoint";
import TopOperationButton from "../CommonComponents/TopOperationButton";
// 本地数据
import {
  pointList,
  outputTypeOption,
  mapTypeOption,
  keyValueOption,
  mapList,
} from "./js/localData";
import KeyValue from "./components/KeyValue.vue";
import { mapGetters } from "vuex";
import {
  getSourceMapList,
  setSourceMapList,
  getMapKeyValobj,
  getMapKeyValArr,
  setCheck,
  valiType,
} from "./js/index";
import _ from "lodash";
export default {
  components: { TabPoint, KeyValue, TopOperationButton },
  props: {
    nodeDataRight: {
      type: Object,
      default: () => {},
    },
    keyNumber: { type: Number },
  },
  computed: {
    ...mapGetters(["metadata", "succSin"]),
    validatorForm() {
      return function (rule, value, callback, item) {
        // 如果没选中,直接返回
        if (item.isCheck === false) {
          callback();
        }
        const msg = valiType(value, item.type);
        if (msg.length === 0) {
          callback();
        } else {
          callback(new Error(msg));
        }
      };
    },
    // 自定义校验自定义属性的参数
    validator() {
      return function (rule, value, callback) {
        var reg = /^[a-zA-Z][-_a-zA-Z0-9]{0,5}/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(
            new Error("属性名称首位必须为字母且不能包含特殊符号和空格!!")
          );
        }
      };
    },
  },
  watch: {
    nodeDataRight: {
      handler: async function (newData, oldData) {
        // const metadata = await this.getMetadata();

        // metadata添加一个选中标识
        this.sources = setCheck(this.succSin.sources);
        this.mapList = setCheck(this.succSin.sourceMap);
        if ("" !== newData && newData != undefined) {
          let tempdata = JSON.parse(JSON.stringify(newData));
          this.newData = tempdata;
          // 取后一个节点属性
          const { attributeList } = tempdata.relateData.targetCell;
          this.form.attributeList = attributeList.map((item) => {
            return {
              ...item,
              defaultValue: "",
            };
          });
          const { objectState, options, map } = tempdata;
          if (tempdata.relateData.targetCell.name != undefined) {
            this.newData.connectedElementName =
              tempdata.relateData.targetCell.name;
          }
          this.form.type = tempdata.type || "";

          // 取出来原始的source数组
          const parameters =
            this.sources.find((item) => item.name == tempdata.type)
              ?.parameters || [];
          // 回显输入框组
          if (options) {
            const scuObj = setSourceMapList(options, parameters);
            const scuOptions = scuObj.options;
            this.form.sourceList = scuOptions;
            this.form.customOption = scuObj.customOption;
          }
          if (map) {
            this.form.mapping = map.type;
            const mapParameters =
              this.mapList.find((item) => item.name == map.type)?.parameters ||
              [];

            const mapObj = setSourceMapList(map.options, mapParameters);
            // map对应关系
            if (map.payloadOrAttribute) {
              if (map.payloadOrAttribute.annotationType == "PAYLOAD") {
                this.form.attTextarea =
                  map.payloadOrAttribute.value &&
                  map.payloadOrAttribute.value.length !== 0 &&
                  map.payloadOrAttribute.value[0];
              } else {
                this.form.attributeList = getMapKeyValArr(
                  map.payloadOrAttribute.value
                );
              }
              this.form.isCorresponding = map.payloadOrAttribute.annotationType
                ? true
                : false;
              this.form.isKeyAtt =
                map.payloadOrAttribute.annotationType || "ATTRIBUTES";
            } else {
              this.form.isCorresponding = false;
            }

            this.form.customOptionMAP = mapObj.customOption;

            this.form.mapList = mapObj.options;
          } else {
            this.form.customOptionMAP = [];
            this.form.mapList = [];
          }
        }
      },
      immediate: true,
      deep: true,
    },
    keyNumber: {
      handler: function (newData, oldData) {},
      immediate: true,
    },
  },
  data() {
    return {
      mapList: [],

      newData: {
        connectedElementName: "",
        type: "",
        options: [],
        annotationType: "SOURCE",
        map: {
          options: [],
          payloadOrAttribute: {},
          type: "",
        },
      },
      form: {
        attTextarea: "",
        isKeyAtt: "ATTRIBUTES",
        mapping: "passThrough(default)",
        partition: false,
        customOption: [],
        customOptionMAP: [],
        options: [],
        sourceList: [],
        mapList: [],
        attributeList: [],
        type: "",
        isCorresponding: false,
      },
      pointList: pointList,
      outputTypeOption: outputTypeOption,
      mapTypeOption: mapTypeOption,
      keyValueOption: keyValueOption,
      sources: [],
    };
  },
  mounted() {},
  methods: {
    handClose() {
      this.$emit("handClose");
    },
    submit() {
      // const data = this.sourceList
      // 选项+自定义选项
      this.$refs["formName"].validate((valid) => {
        if (valid) {
          const sourceOption = getSourceMapList(this.form.sourceList);
          const customOption = getSourceMapList(this.form.customOption);
          this.newData.options = _.concat(sourceOption, customOption);
          // map选项+自定义选项
          const mapOption = getSourceMapList(this.form.mapList);

          const customOptionMAP = getSourceMapList(this.form.customOptionMAP);
          if (!this.newData.map) {
            this.newData.map = {};
          }

          this.newData.map.type = this.form.mapping || "passThrough";
          this.newData.type = this.form.type;
          this.newData.map.options = _.concat(mapOption, customOptionMAP);
          if (this.form.isCorresponding) {
            if (!this.newData.map.payloadOrAttribute) {
              this.newData.map.payloadOrAttribute = {};
            }

            this.newData.map.payloadOrAttribute.annotationType =
              this.form.isKeyAtt;
            if (
              this.newData.map.payloadOrAttribute.annotationType == "PAYLOAD"
            ) {
              this.newData.map.payloadOrAttribute.value = [
                this.form.attTextarea,
              ];
              this.newData.map.payloadOrAttribute.type = "LIST";
            } else {
              this.newData.map.payloadOrAttribute.value = getMapKeyValobj(
                this.form.attributeList
              );
              this.newData.map.payloadOrAttribute.type = "MAP";
            }
          } else {
            this.newData.map.payloadOrAttribute = undefined;
          }
          this.newData.annotationType = "SOURCE";
          this.newData.map.type = this.newData.map.type;
          if (this.newData.map.type.indexOf("passThrough") != -1) {
            this.newData.map.type = "passThrough";
          }
          this.newData.name = this.form.type;
          let returnData = {
            display: false,
            type: "sourceList",
            objectState: this.nodeDataRight.objectState,
            nodeData: this.newData,
            nodeDataRight: this.nodeDataRight,
          };
          this.$emit("returnSource", returnData);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    changeMap(name) {
      // mapList
      this.form.mapList = _.cloneDeep(
        this.mapList.find((item) => item.name == name)?.parameters || []
      );
      this.form.mapList.sort((a, b) => a.optional - b.optional);
    },
    changeType(name) {
      this.form.sourceList = _.cloneDeep(
        this.sources.find((item) => item.name == name)?.parameters || []
      );
      this.form.sourceList.sort((a, b) => a.optional - b.optional);
      this.form.type = name;
    },
    handAddOption(key) {
      this.form[key].push({
        name: "",
        defaultValue: "",
        isCheck: true,
      });
    },
    handDel(index, key) {
      this.form[key].splice(index, 1);
    },
  },
};
</script>

<style lang="scss" scoped>
.key_val_list {
  max-height: 600px;
  overflow-y: auto;
}
.output_sink {
  display: flex;
  /deep/ .el-tabs__header {
    height: 80vh;
  }
  .key_value_list {
    padding: 15px;
    /* padding-bottom: 0; */
    background: rgba(233, 233, 233, 0.3);
    .key_v_btn {
      height: 32px;
      width: 100%;
      border: 1px solid #999999;
      display: flex;
      align-items: center;
      justify-content: center;

      border-radius: 6px;
      cursor: pointer;
      span {
        font-size: 12px;
        color: #666;
      }
    }
  }
}
.option_box {
  height: 80vh;
  width: 100%;
  overflow-y: auto;
  padding-right: 10px;
  /deep/ .el-select {
    width: 100%;
  }
  /deep/ .el-form-item__label {
    padding-bottom: 0 !important;
    width: auto;
  }
  /deep/ .el-form-item {
    margin-bottom: 0;
    width: 100%;
  }
  /deep/ .el-radio {
    margin-right: 0;
  }

  .title {
    color: #333333;
    font-size: 16px;
    font-weight: bold;
  }
}
</style>
